package com.open.launcher.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearSmoothScroller;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.open.launcher.R;
import com.open.launcher.adapter.ChanelAllAdapter;
import com.open.launcher.adapter.MainChanelAdapter;
import com.open.launcher.adapter.ProgramAdapter;
import com.open.launcher.presenter.AllChannelsPresenter;
import com.open.launcher.utils.APPLog;
import com.open.launcher.utils.Consts;
import com.open.launcher.utils.Paths;
import com.open.launcher.view.MyRecycleView;
import com.open.library.utils.PreferencesUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Shinelon on 2017/11/8.
 */

public class PlayWindowFragment extends Fragment implements AllChannelsPresenter.Callback {
    private PlayerActivity mContext;
    private MyRecycleView mOne_stage_rv;
    private MyRecycleView mTwo_stage_rv;
    private MyRecycleView mThree_stage_rv;
    private View mline_two;
    private View mline_one;
    private AllChannelsPresenter allChannelsPresenter;
    private int focusPosition;
    private MainChanelAdapter firstAdapter;
    private ChanelAllAdapter sencondAllAdapter;
    private ProgramAdapter thirdAdapter;
    private View view;
    private FragmentManager fragmentManager;
    private int FIRST_LIST= 0x1;
    private int HIDE_FRAGMENT = 0x2;
    private Handler mainHandler;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == FIRST_LIST){
                mOne_stage_rv.requestFocus();
                firstAdapter.selected();
            }
            else if(msg.what == HIDE_FRAGMENT){
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
            }
        }
    };
    public void setContext(PlayerActivity context){
        this.mContext = context;
    }
    public void setFragmentManager(FragmentManager fragmentManager){
        this.fragmentManager = fragmentManager;
    }
    public void setMainHandler(Handler handler){
        this.mainHandler = handler;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_winow, container, false);
        initWindow();
        return view;
    }

    public void initWindow() {
        initView();
        initData();
        setLisenter();
        mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT,5000);
    }

    private void initView() {
        mOne_stage_rv = (MyRecycleView) view.findViewById(R.id.one_stage_rv);
        mTwo_stage_rv = (MyRecycleView) view.findViewById(R.id.two_stage_rv);
        mThree_stage_rv = (MyRecycleView) view.findViewById(R.id.three_stage_rv);
        mline_two = view.findViewById(R.id.line_two);
        mline_one = view.findViewById(R.id.line_one);
    }

    private void initData() {
        allChannelsPresenter = new AllChannelsPresenter(mContext);
        allChannelsPresenter.setDisplayed(true);
        Bundle bundle = new Bundle();
        bundle.putString("url", "http://"+ PreferencesUtils.getString(mContext, Consts.IP_ADDR_KEY) +":"+PreferencesUtils.getString(mContext, Consts.IP_ADDR_PORT) +Paths.CHANNEL_PATH);
        allChannelsPresenter.loadItem(bundle, this);
        mOne_stage_rv.setFocusable(false);
        mTwo_stage_rv.setFocusable(false);
        mThree_stage_rv.setFocusable(false);

        //Toast.makeText(mContext, "开始加载数据", Toast.LENGTH_SHORT).show();

    }

    private void setLisenter() {
        allChannelsPresenter.onBindAllChannels(channelsViewHolder);
        mOne_stage_rv.setOnKeyListener(new FirstChannelOnKey());
        mTwo_stage_rv.setOnKeyListener(new SencondChannelOnKey());
        mThree_stage_rv.setOnKeyListener(new ThirdChannelOnKey());
        mOne_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    mOne_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            if(mOne_stage_rv.getChildCount()>0){
                                firstAdapter.selected();
                            }
                        }
                    });
                }
            }
        });
        mTwo_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mTwo_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mTwo_stage_rv.getChildCount() > 0) {
                                sencondAllAdapter.selected();
                            }
                        }
                    });
                }
            }
        });
        mThree_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mThree_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            //Toast.makeText(mContext, "获取到焦点", Toast.LENGTH_SHORT).show();
                            if (mThree_stage_rv.getChildCount() > 0) {
                                thirdAdapter.selected();
                            }
                        }
                    });
                }
            }
        });
    }


    @Override
    public void onError(int code, String msg) {

    }

    @Override
    public void onMovieCompleted(AllChannelsPresenter presenter, int count) {
        firstAdapter = new MainChanelAdapter(presenter);
        mOne_stage_rv.setLayoutManager(new FocusGridLayoutManager(mContext, 1));
        firstAdapter.setCount(count);
        mOne_stage_rv.setAdapter(firstAdapter);
        if (LauncherApplication.memPosition.size()==2) {
            firstAdapter.position = LauncherApplication.memPosition.get(0);
        }
        mOne_stage_rv.setFocusable(true);
        try {
            Runtime.getRuntime().exec("input keyevent 22");
        } catch (IOException e) {
            e.printStackTrace();
        }
        mHandler.sendEmptyMessageDelayed(FIRST_LIST,300);
        APPLog.printInfo("设置直播数据适配器");
    }

    @Override
    public void onChannelCompleted(AllChannelsPresenter presenter, int count) {
        sencondAllAdapter = new ChanelAllAdapter(presenter);
        FocusGridLayoutManager manager = new FocusGridLayoutManager(mContext, 1);
        mTwo_stage_rv.setLayoutManager(manager);
        sencondAllAdapter.setCount(count);
        sencondAllAdapter.setMainHandler(mainHandler);
        mTwo_stage_rv.setAdapter(sencondAllAdapter);
        if (LauncherApplication.memPosition.size()==2) {
            sencondAllAdapter.position = LauncherApplication.memPosition.get(1);
        }
        mTwo_stage_rv.setFocusable(true);
    }

    @Override
    public void onProgramCompleted(AllChannelsPresenter presenter, int count) {
        thirdAdapter = null;
        thirdAdapter = new ProgramAdapter(presenter, mContext);
        mThree_stage_rv.setLayoutManager(new FocusGridLayoutManager(mContext, 1));
        thirdAdapter.setCount(count);
        thirdAdapter.setMainHandler(mainHandler);
        mThree_stage_rv.setAdapter(thirdAdapter);
        mThree_stage_rv.setFocusable(true);
    }

    private AllChannelsPresenter.AllChannelsViewHolder channelsViewHolder = new AllChannelsPresenter.AllChannelsViewHolder() {
        @Override
        public void setmThreeStageRv(boolean isShow) {
            if (isShow) {
                mThree_stage_rv.setVisibility(View.VISIBLE);
            } else {
                mThree_stage_rv.setVisibility(View.GONE);
            }
        }

        @Override
        public void setLineTwoView(boolean isShow) {
            if (isShow) {
                mline_two.setVisibility(View.VISIBLE);
            } else {
                mline_two.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void setLineOneView(boolean isShow) {
            if (isShow) {
                mline_one.setVisibility(View.VISIBLE);
            } else {
                mline_one.setVisibility(View.INVISIBLE);
            }
        }
    };

    public class FirstChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if(mHandler.hasMessages(HIDE_FRAGMENT)){
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT,5000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = firstAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = firstAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                mTwo_stage_rv.requestFocus();

                return true;
            }else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
                return true;
            }else if(keyCode == KeyEvent.KEYCODE_BACK&&event.getAction() == KeyEvent.ACTION_DOWN){
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return true;
        }
    }

    public class SencondChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if(mHandler.hasMessages(HIDE_FRAGMENT)){
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT,5000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = sencondAllAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = sencondAllAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                mThree_stage_rv.requestFocus();
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) && event.getAction() == KeyEvent.ACTION_DOWN) {
                sencondAllAdapter.onClick();
                LauncherApplication.memPosition.clear();
                LauncherApplication.memPosition.add(firstAdapter.position);
                LauncherApplication.memPosition.add(sencondAllAdapter.position);
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT&&event.getAction() == KeyEvent.ACTION_DOWN){
                LauncherApplication.memPosition.clear();
                mOne_stage_rv.requestFocus();
                return true;
            }else if(keyCode == KeyEvent.KEYCODE_BACK&&event.getAction() == KeyEvent.ACTION_DOWN){
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return false;
        }
    }

    public class ThirdChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if(mHandler.hasMessages(HIDE_FRAGMENT)){
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT,5000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = thirdAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = thirdAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT&&action == KeyEvent.ACTION_DOWN) {
                    mTwo_stage_rv.requestFocus();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) && action == KeyEvent.ACTION_DOWN) {
                thirdAdapter.onClick();
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
                return true;
            }else if(keyCode == KeyEvent.KEYCODE_BACK&&event.getAction() == KeyEvent.ACTION_DOWN){
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return false;
        }
    }
}
